<template>
  <div class="box" id="box">
    <div class="search_header">
      <a class="leftback" @click="$router.go(-1)">
        <van-icon name="arrow-left" />
      </a>
      <!-- 1.搜索框-事件监听 -->
      <form action="/">
        <van-search
          v-model="value"
          show-action
          clearable
          placeholder="请输入关键词搜索"
          @search="onSearch"
          @cancel="onCancel"
        />
      </form>
    </div>
    <!-- 2.搜索组件：当触发搜索事件时，显示搜索结果 -->
    <div v-if="flag">
        <SearchDetail :prolist="prolist" v-if="searchFlag"></SearchDetail>
        <div v-else>
          <h1 style="text-align:center;line-height:1rem;">没有搜到相关内容</h1>
          <Recomment></Recomment>
        </div>
    </div>
    <!-- 3.默认显示：热门关键词及推荐组件  当用户有搜索历史值时出现历史记录 -->
    <div v-else>
    <!-- 3.1.热门关键词 -->
    <div class="hotword">
      <h1>大家都在搜<van-icon name="replay"  size=".16rem" color="orange" style="margin-left:.1rem;font-weight: bold;" @click="refrensh()"/></h1>
      <ul>
        <li v-for="(item, index) of hotword1" :key="index" @click="hot(item)">{{item}}
        </li>
      </ul>
    </div>
    <!-- 3.2.历史记录 -->
    <div class="hotword history" v-if="historyFlag">
      <h1>历史记录</h1>
      <ul>
        <li v-for="(item, index) of history1" :key="index"  @click="isselect(item)" :class="item.isselect?'b':''">{{item.name}}
        <van-icon name="cross" :class="item.isselect?'cancel':'cancel-o'" @click.stop="delete1(index)"/>
        </li>
      </ul>
    </div>
    <!-- 3.3.推荐组件 -->
    <Recomment></Recomment>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Search, NavBar, Icon, Toast } from 'vant'
import { getSearch } from '@/api'
import Recomment from '@/components/recomment.vue'
import SearchDetail from '@/components/searchDetail.vue'
Vue.use(Search)
Vue.use(NavBar)
Vue.use(Icon)
Vue.use(Toast)
export default {
  data () {
    return {
      searchFlag: false, // 搜索内容是否为空，默认为假
      flag: false, // 为真时显示搜索组件
      prolist: [], // 搜索结果
      value: '', // 搜索值
      hotword: ['皮肤美白', '面部提升', '脂肪瘦身', '双眼皮', '牙齿矫正', '隐痕', '美眼弧线', '光子嫩肤', '美白淡斑', '细致毛孔', '润百颜', '水光针', '深层补水'],
      hotword1: [], // 暂存热门关键词
      group: 0, // 计算关键词分组
      count: 1, // 点击换一换的次数
      shownum: 5, // 显示关键字个数
      historyFlag: false, // 历史记录出现与否
      history: [], // 历史记录值
      history1: [] // 暂存历史记录值
    }
  },
  components: {
    Recomment,
    SearchDetail
  },
  methods: {
    // 点击热门关键词，直接显示对应搜索内容
    hot (val) {
      this.onSearch(val)
      this.value = val
    },
    // 计算换一换分组长度
    listen (num) {
      // 获取存储关键词数组的长度
      const len = this.hotword.length
      // 限定一组为num个，计算一共有几组，若不能整除则加一
      this.group = len / num
      if (len % num !== 0) {
        this.group = parseInt(this.group) + 1
      }
    },
    // 点击换一换关键词事件
    refrensh () {
      // console.log(this.count, this.group)
      this.hotword1 = this.hotword.slice(
        this.count * this.shownum,
        (this.count + 1) * this.shownum
      )
      // console.log(this.hotword1)
      // 若点击次数超过分组数，则重新开始
      if (this.count >= this.group - 1) {
        this.count = 0
      } else {
        this.count++
      }
    },
    // 历史记录点击事件
    isselect (item) {
      item.isselect = !item.isselect
      // console.log(item.isselect)
    },
    // 搜索事件：点击键盘搜索按键或回车时触发
    onSearch (val) {
      // console.log(val)
      // 根据搜索框内value值，进行模糊搜索，显示相对于搜索内容
      // 当搜索框内容不为空时
      if (val !== '') {
        getSearch({ value: val }).then(res => {
        // 显示搜索结果
          this.flag = true
          this.prolist = res.data.data
          // 当搜索内容为空时显示“没有搜到相关内容”
          if (this.prolist !== null) {
            this.searchFlag = true
          } else {
            this.searchFlag = false
          }
        })
        // 存储历史记录
        this.history.push({ name: val })
        this.history.forEach(item => {
          this.$set(item, 'isselect', false)
        })
        localStorage.setItem('historyData', JSON.stringify(this.history))
        // console.log(this.history)
      // 当搜索框为空时
      } else {
        Toast('请输入搜索关键词')
      }
      // console.log(this.prolist)
    },
    // 历史记录删除事件
    delete1 (index) {
      this.history.splice(index, 1)
      if (this.history.length === 0) {
        this.historyFlag = false
        localStorage.removeItem('historyData')
        this.history1 = JSON.parse(localStorage.getItem('historyData'))
      } else {
        localStorage.setItem('historyData', JSON.stringify(this.history))
        this.history1 = JSON.parse(localStorage.getItem('historyData'))
      }
      // console.log(this.history.length)
    },
    // 取消事件：当取消时，回复默认显示内容
    onCancel () {
      this.flag = false
      /* 对历史记录应作出有效期规划--暂未实现 */
      localStorage.setItem('historyData', JSON.stringify(this.history))
      this.history1 = JSON.parse(localStorage.getItem('historyData'))
      // console.log(this.history1)
      if (this.history1.length !== 0) {
        this.historyFlag = true
      }
      // console.log('取消')
    }
  },
  mounted () {
    // 计算分组
    this.listen(this.shownum)
    // 默认显示热门关键词1
    this.hotword1 = this.hotword.slice(this.count - 1, this.shownum)
    // 查询是否有历史记录，有则渲染
    // console.log(this.history, typeof (localStorage.historyData))
    if (this.history !== '' && typeof (localStorage.historyData) !== 'undefined') {
      this.history = JSON.parse(localStorage.getItem('historyData'))
      this.history1 = JSON.parse(localStorage.getItem('historyData'))
      this.historyFlag = true
    }
  },
  watch: {
    // 监听搜索框中内容，当搜索框内无内容时，恢复默认显示内容
    value () {
      if (this.value === '') {
        this.onCancel()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.van-search {
  padding: 0.07rem 0.1rem;
}
/deep/.van-search .van-cell {
  width: .2895rem;
  height: .3rem;
  padding:  0;
  line-height: .3rem;
}
/deep/.van-field__left-icon .van-icon, .van-field__right-icon .van-icon{
  font-size: .15rem;
  padding-left: .09rem;
}
/deep/.van-search__content {
  border-radius: .125rem;
  padding-left: 0;
}
/deep/.van-field__control {
  font-size: .12rem;
}
/deep/.van-search__action{
  font-size: .12rem;
  color: #333333;
  font-weight: bold;
  padding-left: .165rem;
}
/deep/.van-field__clear {
    font-size: .16rem;
}
/deep/.van-field__clear, .van-field__right-icon {
    margin-right: -0.08rem;
    padding: 0 .08rem;
}
.search_header {
  width: 100%;
  height: 0.46rem;
  padding: 0 0.2rem;
  a {
    display: inline-block;
    height: 0.46rem;
  }
}
.leftback{
    float: left;
    width: 0.2rem;
    height: 0.46rem;
    // background: rgba(193, 193, 193, 0.2);
    // border-radius: 50%;
    text-align: center;
    .van-icon-arrow-left {
      position: relative;
      top: 0;
      float: left;
      font-size: 0.2rem;
      color: #464646;
      line-height: 0.46rem;
    }
}
.hotword {
  width: 100%;
  padding:.22rem 0 0 .1rem;
  overflow: auto;
  h1 {
    color: #333333;
    font-size: .12rem;
  }
  ul {
    padding:.23rem 0 .09rem .1rem;
    li {
    float: left;
    margin-right: .25rem;
    margin-bottom: .15rem;
    -webkit-transform-origin-x: 0;
    -webkit-transform: scale(0.917);
    background-color: #FFF8F8;
    border-radius: .065rem;
    width: .615rem;
    // height: .185rem;
    text-align: center;
    padding: .035rem 0;
    position: relative;
   }
   .b {
     background-color: #ff78a3;
     color: #fff;
    }
  }
}
.history {
  padding-top: .1rem;
}
.cancel{
    position: absolute;
    top: -.04rem;
    background: #aaa;
    color: white;
    border-radius: 50%;
    padding: .01rem;
    right:0;
}
.cancel-o {
  display: none;
}
/deep/.van-toast {
    width: .88rem!important;
    min-height: .88rem!important;
    padding: .16rem!important;
    font-size: .14rem!important;
    line-height: .2rem!important;
    border-radius: .08rem!important;
}
</style>
